/**
 * 防抖
 * @param fn 执行的回调函数
 * @param time 间隔时间
 * @param triggleNow 是否先执行
 * @returns 
 */
export function debounce( fn: Function, time: number, triggleNow: boolean = true ) {
  let t: number | null = null;

  const debounced = ( ...args: any[] ) => {
    let res;

    if( t ) {
      clearTimeout(t);
    }

    if( triggleNow ) {
      const exec = !t;

      t = setTimeout(() => t = null, time);

      if( exec ){
        res = fn( ...args );
      } 
    } else {
      t = setTimeout(() => res = fn( ...args ), time);
    }

    return res;
  }

  debounced.removeTimer = () => {
    clearTimeout( t as number );
    t = null;
  }

  return debounced;
}

/**
 * 节流
 * @param fn 回调函数
 * @param time 间隔时间
 * @returns 
 */
export function throttle( fn: Function, time: number ) {
  let t: number | null = null;
  let begin: number = new Date().getTime();

  return ( ...args: any[] ) => {
    const cur = new Date().getTime();
    let res;

    if( t ) {
      clearTimeout( t );
    }

    if( cur - begin >= time ){
      res = fn( ...args );
      begin = cur;
    } else {
      t = setTimeout( () => res = fn( ...args ), time );
    }

    return res;
  }
}